#!/usr/bin/env python

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import XML
from utils.singleton import singleton
import server as serv
import os

@singleton
class Conf():
    def __init__(self):
        self.ETree=ElementTree()
        self._servers={}
        self._serversRoot={}
        self.read()
        
    def read(self):
        self.xml=self.ETree.parse("conf/conf.xml")
        servers=self.xml.findall("servers/server")
        currentdrive=os.path.splitdrive(os.path.abspath("."))[0]
        for server in servers:
            name=server.attrib["name"]
            if not self._servers.has_key(name):
                self._servers[name]={}
            self._servers[name]=self._getPaths(server)
            
            paths=server.find("paths").attrib["root"]
            paths.replace("${CurrentDrive}",currentdrive)
            print paths
            self._serversRoot[name]=paths
    
    def _getPaths(self,serverNode):
        paths=serverNode.findall("paths/path")
        ret={}
        for path in paths:
            name=path.attrib["name"]
            ret[path.text]=name
        return ret
            
    
    def save(self):
        xservers=self.xml.find("servers")
        xservers.clear()
        currentdrive=os.path.splitdrive(os.path.abspath("."))[0]
        for serverName in self._servers:
            server=serv.Servers().getServerByName(serverName)
            if not server:
                continue
            node='<server name="'+serverName+'">'
            node+='<paths root="'+server.getDocumentRoot()+'">'
            paths=server.getPaths()
            
            for path in server.getPaths():
                drive=os.path.splitdrive(path)[0]
                path2=path
                if drive==currentdrive:
                    path2="${CurrentDrive}"+path2[len(drive):]
                print path2
                node+='<path name="'+paths[path]+'">'+path2+'</path>'
            node+='</paths>'
            node+='</server>'
            xnode=XML(node)
            xservers.append(xnode)
        self.ETree.write("conf/conf.xml","utf_8")
    
    def getServerRoot(self,name):
        if not self._serversRoot.has_key(name):
            self._serversRoot[name]={}
        return self._serversRoot[name]
        
    def getServerPaths(self,name):
        if not self._servers.has_key(name):
            self._servers[name]={}
        return self._servers[name]
    
    def setServerPath(self,name,paths):
        self._servers[name]=paths
        
    def addServer(self,name):
        self._servers[name]={}
    